package com.fine.hair.manage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fine.hair.comm.dto.*;
import com.fine.hair.comm.enums.ItemType;
import com.fine.hair.comm.enums.OrderStatus;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.PageInfo;
import com.fine.hair.comm.utils.Utils;
import com.fine.hair.comm.wx.WxClient;
import com.fine.hair.manage.mapper.*;
import com.fine.hair.manage.service.OrderService;
import com.fine.hair.manage.service.OrderTaskService;
import com.fine.hair.manage.service.UserService;
import com.fine.hair.manage.util.JwtUtil;
import com.fine.hair.comm.model.Item;
import com.fine.hair.comm.model.Order;
import com.fine.hair.comm.model.SecUser;
import com.fine.hair.comm.model.User;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>预约控制层</p>
 *
 * @author mouseyCat
 * @date 2020/10/24 15:16
 */
@Api(tags = {"(订单)预约相关接口"})
@RestController
@RequestMapping("/reservation/")
public class ReservationController {

    @Resource
    private OrderMapper orderMapper;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private SecUserMapper secUserMapper;

    @Resource
    private ItemMapper itemMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderTaskService orderTaskService;

    @Autowired
    private UserService userService;


    @PostMapping("reservation-list")
    @ApiOperation("预约订单列表")
    public ApiResponse<PageInfo<Order>> reservationList(HttpServletRequest request, @RequestBody ReservationListDto dto) {

        if (StrUtil.isNotBlank(dto.getStartTime())) {
            // 处理 开始时间 和 结束时间
            String[] customDayStartAndEnd = getCustomDayStartAndEnd(dto.getStartTime(), dto.getEndTime());
            dto.setStartTime(customDayStartAndEnd[0]);
            dto.setEndTime(customDayStartAndEnd[1]);
        }
        String username = jwtUtil.getUsernameFromJWT(jwtUtil.getJwtFromRequest(request));
        SecUser secUser = secUserMapper.selectByUsername(username);
        PageInfo<Order> pageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        List<Order> orderList = Lists.newArrayList();
        BigDecimal userIntegral = BigDecimal.ZERO;
        // 3 为门店管理员
        if (secUser.getRoleId() == 3) {
            // 筛选门店
            orderList = orderMapper.selectReservationList(pageInfo, secUser.getBranchId(), dto);
            for (Order order : orderList) {
                order.setOrderStatusInt(Integer.valueOf(order.getOrderStatus()));
                User user = userMapper.selectById(order.getUserId());
                order.setCustomerName(user.getNickName());
                order.setCustomerAvatar(user.getHeadPhoto());
                order.setCustomerBirth(user.getBirth());
                order.setBirth(user.getBirth());
                order.setCustomerPhone(user.getPhoneNumber());
                userIntegral =  orderMapper.selectUserIntegral(user.getId());
                order.setRemark(user.getRemark());
                order.setScore(userIntegral==null?BigDecimal.ZERO.toString():userIntegral.toString());
                order.setOrderStatus(OrderStatus.fromCode(Integer.valueOf(order.getOrderStatus())).getMessage());
                order.setItemType(ItemType.fromCode(Integer.valueOf(order.getItemType())).getMessage());
            }
            pageInfo.setRecords(orderList);
        }
        // 1 为超级管理员
        else if (secUser.getRoleId() == 1) {
            // 不筛选门店
            orderList = orderMapper.selectReservationListNoneBranchIds(pageInfo, dto);
            for (Order order : orderList) {
                order.setOrderStatusInt(Integer.valueOf(order.getOrderStatus()));
                User user = userMapper.selectById(order.getUserId());
                order.setCustomerName(user.getNickName());
                order.setCustomerPhone(user.getPhoneNumber());
                order.setCustomerAvatar(user.getHeadPhoto());
                order.setCustomerBirth(user.getBirth());
                order.setBirth(user.getBirth());
                userIntegral =  orderMapper.selectUserIntegral(user.getId());
                order.setRemark(user.getRemark());
                order.setScore(userIntegral==null?BigDecimal.ZERO.toString():userIntegral.toString());
                order.setOrderStatus(OrderStatus.fromCode(Integer.valueOf(order.getOrderStatus())).getMessage());
                order.setItemType(ItemType.fromCode(Integer.valueOf(order.getItemType())).getMessage());
            }
            pageInfo.setRecords(orderList);
        }
        // 财务管理员
        else {
            // 不给数据
            pageInfo.setRecords(orderList);
        }
        return ApiResponse.ofSuccess(pageInfo);
    }

    @PutMapping("alter-reservation")
    @ApiOperation("修改预约订单")
    public ApiResponse alterReservation(@RequestBody AlterReservationDto dto) {
        Item item = itemMapper.selectById(dto.getItemId());
        if(Objects.isNull(item)){
            return ApiResponse.ofFailed("项目不存在");
        }
        Order order = new Order();
        BeanUtil.copyProperties(dto, order);
        order.setId(dto.getOrderId());
        order.setUserId(dto.getUserId());
        order.setTechnicianId(dto.getTechnicianId());
        User technician = userMapper.selectById(dto.getTechnicianId());
        order.setItemId(dto.getItemId());
        order.setItemTitle(item.getTitle());
        order.setTechnicianAvatar(technician.getHeadPhoto());
        order.setTechnicianName(technician.getNickName());
        order.setTechnicianPhone(technician.getPhoneNumber());
        order.setExecuteTime(DateUtil.parseDateTime(dto.getExecuteTime()));
        order.setRemark(dto.getRemark());
        orderMapper.updateById(order);
        return ApiResponse.ofSuccess();
    }

    @DeleteMapping("del-Reservation/{orderId}")
    @ApiOperation("删除预约订单")
    public ApiResponse delReservation(@PathVariable String orderId) {
        orderMapper.deleteById(orderId);
        return ApiResponse.ofSuccess();
    }

    @PostMapping("add-reservation")
    @ApiOperation("增加预约订单")
    public ApiResponse addReservation(@RequestBody AddReservationDto dto) {
        Item item = itemMapper.selectById(dto.getItemId());
       /* if (item.getStock() < 1) {
            return ApiResponse.ofStatus(MyStatus.STOCK_NOT_ENOUGH);
        }*/
        // 判断技师是否请假
        Date executeTime = DateUtil.parseDateTime(dto.getExecuteTime());
        executeTime.setTime(executeTime.getTime() + item.getTime() * 60 * 1000);
        LocalDateTime orderTime = LocalDateTime.ofInstant(executeTime.toInstant(), ZoneId.systemDefault());
        int count = leaveMapper.selectLeaveCountByOrderTime(orderTime, Long.valueOf(dto.getTechnicianId()));
        if (count > 0) {
            return ApiResponse.ofFailed("该技师已请假，暂不提供服务...");
        }

        // 判断该技师是否有订单
        int orderConut = orderMapper.selectBusyCountByOrderTime(DateUtil.parseDateTime(dto.getExecuteTime()),dto.getTechnicianId());
        if (orderConut > 0) {
            return ApiResponse.ofFailed("该技师忙碌中，请稍后...");
        }
        Order order = new Order();
        order.setId(snowflake.nextIdStr());
        BeanUtil.copyProperties(dto, order);

        /*item.setStock(item.getStock() - 1);
        itemMapper.updateById(item);*/
        order.setItemType(item.getType().toString());
        order.setItemTitle(item.getTitle());
        order.setItemPrice(item.getPrice());
        order.setItemImage(item.getImage());
        order.setItemId(item.getId().toString());
        order.setItemContent(item.getContent());
        order.setItemTime(item.getTime());
        orderMapper.insert(order);
        return ApiResponse.ofSuccess();
    }

    @PostMapping("add-reservation-batch")
    @ApiOperation("批量增加预约订单")
    public ApiResponse addReservationBatch(@RequestBody AddReservationBatchDto dto) {
        return orderService.addReservationBatch(dto);
    }

    @PostMapping("auto-add-reservation-batch")
    @ApiOperation("自动批量增加预约订单")
    public ApiResponse addReservationBatch(@RequestBody AutoAddReservationBatchDto dto) {
        return orderService.autoAddReservationBatch(dto);
    }

    @PostMapping("change-order-status")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("更改订单状态")
    public ApiResponse changeOrderStatus(@RequestBody ChangeOrderStatusDto dto) {
        if (OrderStatus.COMPLETED.getCode().toString().equals(dto.getOrderStatus()) || OrderStatus.STARTING.getCode().toString().equals(dto.getOrderStatus())) {
            Order order = orderService.getById(dto.getOrderId());
            if (ObjectUtil.isNull(order)) {
                throw new BusinessException("当前订单不存在");
            }
            order.setOrderStatus(dto.getOrderStatus());
            // 同步用户次数
            User user = userService.getById(order.getUserId());
            if (ObjectUtil.isNull(user)) {
                throw new BusinessException("当前订单的客户在系统中不存在");
            }
            if(dto.getOrderStatus().equals("2")){
                orderTaskService.updateUserServiceCount(user, order);
                Item item = itemMapper.selectById(order.getItemId());
                WxClient.orderSecc(user.getOpenId(), Utils.format(new Date(), "yyyy-MM-dd HH:mm:ss"),"订单完成",item.getTitle(),Utils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss"),order.getId());
            }
            if(dto.getOrderStatus().equals("4")){
                order.setExecuteTime(new Date());
            }
            orderService.updateById(order);
            return ApiResponse.ofSuccess();
        } else {
            throw new BusinessException("只能将状态更改为已完成");
        }

    }

    /**
     * 处理查询时自定义的开始时间和结束时间
     *
     * @param start 日期 格式 yyyy-MM-dd
     * @param end   日期 格式 yyyy-MM-dd
     * @return 开始时间和结束时间的数组 下标0 为开始时间 下标1 为结束时间
     */
    public static String[] getCustomDayStartAndEnd(String start, String end) {
        // 兼容前端传 yyyy-MM-dd HH:mm:ss yyyy-MM-dd 两种情况
        String startTime = start.split(" ")[0] + " 00:00:00";
        String endTime = end.split(" ")[0] + " 23:59:59";
        String[] time = new String[2];
        time[0] = startTime;
        time[1] = endTime;
        return time;
    }

}
